package morenoapp.components.thinkgraphv2.nodes;

import edu.umd.cs.piccolo.nodes.PText;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import morenoapp.components.thinkgraphv2.nodes.partial.PVector;
import morenoapp.model.data.MorenoRespondentFace;
import morenoapp.model.view2.MorenoView2Face;
import morenoapp.util.I18N;

/**
 *
 * @author root
 */
public class CorrectionNode extends VectorItemNode {
    final MorenoRespondentFace respondent;

    public CorrectionNode(MorenoView2Face _config, MorenoRespondentFace _respondent) {
        super(_config);
        this.respondent = _respondent;
        propertyChange(null);
    }



    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        removeAllChildren();

        //do not display anything if respondent is hidden
        if (config.isHideRespondent(respondent) == true) {
            return;
        }

        //getting respondent position
        Point2D position = config.getRespondentPosition(respondent);

        if (config.isDisplayCorrections()) {
            //determine target round (ring number which holds current node correctly)
            int currentRing = getCurrentRing(position);
            int correctRing = getCorrectRing();
            if (currentRing != correctRing) {
                double distanceToCenter = position.distance(0, 0);
                double distanceToCorrectPoint = (correctRing + 0.5) * config.getRingStep();

                double correctionVectorLength = distanceToCorrectPoint - distanceToCenter;
                double normalizedDirectionX = 1.0;
                double normalizedDirectionY = 0.0;
                if (distanceToCenter > 1) {
                    normalizedDirectionX = position.getX() / distanceToCenter;
                    normalizedDirectionY = position.getY() / distanceToCenter;
                }
                double targetX = position.getX() + (normalizedDirectionX * correctionVectorLength);
                double targetY = position.getY() + (normalizedDirectionY * correctionVectorLength);
                this.addChild(new PVector(position.getX(), position.getY(),
                        targetX, targetY,
                        20.0f, 0.0f,
                        new BasicStroke(),
                        Color.red));
                PText text = new PText(I18N.get("sociogram.correct_position"));
                text.setOffset(new Point2D.Double(targetX, targetY));
                text.setPaint(null);
                text.setTextPaint(Color.lightGray);
                text.setPickable(false);
                addChild(text);
            }
        }
    }

    private int getCurrentRing(Point2D position) {
        int currentRing = (int) Math.floor(position.distance(0, 0)) / config.getRingStep();
        return Math.min(3, currentRing);
    }

    private int getCorrectRing() {
        return (int) respondent.getMetricIndividualStatus();
    }
}
